/*
 * Copyright (c) 2009-2010 HIT Microelectronic Center
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *
 * Authors: Gou Pengfei
 *          Jin Yinghan
 *
 * Date: Dec. 2009
 *
 */

#include "config/the_isa.hh"
#include "cpu/edge/map.hh"
#include "params/DerivEdgeCPU.hh"

using namespace std;

template<class Impl>
SimpleEdgeMap<Impl>::SimpleEdgeMap(CPU *_cpu, DerivEdgeCPUParams *params)
    : cpu(_cpu),
      executeToMapDelay(params->executeToMapDelay),
      commitToMapDelay(params->commitToMapDelay),
      fetchToMapDelay(params->fetchToMapDelay),
      mapWidth(params->mapWidth),
      numThreads(params->numThreads)
{
    _status = Inactive;

    // Setup status, make sure stall signals are clear.
    for (ThreadID tid = 0; tid < numThreads; ++tid) {
        mapStatus[tid] = Idle;

        stalls[tid].execute = false;
        stalls[tid].commit = false;
    }

    // @todo: Make into a parameter
    skidBufferMax = (fetchToMapDelay * params->fetchWidth) + mapWidth;
}

template <class Impl>
std::string
SimpleEdgeMap<Impl>::name() const
{
    return cpu->name() + ".map";
}

template <class Impl>
void
SimpleEdgeMap<Impl>::regStats()
{
    mapIdleCycles
        .name(name() + ".MAP:IdleCycles")
        .desc("Number of cycles map is idle")
        .prereq(mapIdleCycles);

    mapBlockedCycles
        .name(name() + ".MAP:BlockedCycles")
        .desc("Number of cycles map is blocked")
        .prereq(mapBlockedCycles);

    mapRunCycles
        .name(name() + ".MAP:RunCycles")
        .desc("Number of cycles map is running")
        .prereq(mapRunCycles);

    mapUnblockCycles
        .name(name() + ".MAP:UnblockCycles")
        .desc("Number of cycles map is unblocking")
        .prereq(mapUnblockCycles);

    mapSquashCycles
        .name(name() + ".MAP:SquashCycles")
        .desc("Number of cycles map is squashing")
        .prereq(mapSquashCycles);

    mapMappedInstBlocks
        .name(name() + ".MAP:MapdInsts")
        .desc("Number of instructions handled by map")
        .prereq(mapMappedInstBlocks);

    mapSquashedInstBlocks
        .name(name() + ".MAP:SquashedInsts")
        .desc("Number of squashed instructions handled by map")
        .prereq(mapSquashedInstBlocks);
}

template<class Impl>
void
SimpleEdgeMap<Impl>::setTimeBuffer(TimeBuffer<TimeStruct> *tb_ptr)
{
    timeBuffer = tb_ptr;

    // Setup wire to write information back to fetch.
    toFetch = timeBuffer->getWire(0);

    // Create wires to get information from proper places in time buffer.
    fromExecute = timeBuffer->getWire(-executeToMapDelay);
    fromCommit = timeBuffer->getWire(-commitToMapDelay);
}

template<class Impl>
void
SimpleEdgeMap<Impl>::setMapQueue(TimeBuffer<Map2Execute> *dq_ptr)
{
    map2executeQueue = dq_ptr;

    // Setup wire to write information to proper place in map queue.
    toExecute = map2executeQueue->getWire(0);
}

template<class Impl>
void
SimpleEdgeMap<Impl>::setFetchQueue(TimeBuffer<Fetch2Map> *fq_ptr)
{
    fetch2mapQueue = fq_ptr;

    // Setup wire to read information from fetch queue.
    fromFetch = fetch2mapQueue->getWire(-fetchToMapDelay);
}

template<class Impl>
void
SimpleEdgeMap<Impl>::setActiveThreads(std::list<ThreadID> *at_ptr)
{
    activeThreads = at_ptr;
}

template <class Impl>
bool
SimpleEdgeMap<Impl>::drain()
{
    // Map is done draining at any time.
    cpu->signalDrained();
    return true;
}

template <class Impl>
void
SimpleEdgeMap<Impl>::takeOverFrom()
{
    _status = Inactive;

    // Be sure to reset state and clear out any old instructions.
    for (ThreadID tid = 0; tid < numThreads; ++tid) {
        mapStatus[tid] = Idle;

        stalls[tid].execute = false;
        stalls[tid].commit = false;
        while (!instBlocks[tid].empty())
            instBlocks[tid].pop();
        while (!skidBuffer[tid].empty())
            skidBuffer[tid].pop();
    }
    wroteToTimeBuffer = false;
}

template<class Impl>
bool
SimpleEdgeMap<Impl>::checkStall(ThreadID tid) const
{
    bool ret_val = false;

    if (stalls[tid].execute) {
        DPRINTF(EdgeMap,"[tid:%i]: Stall fom Execute stage detected.\n", tid);
        ret_val = true;
    } else if (stalls[tid].commit) {
        DPRINTF(EdgeMap,"[tid:%i]: Stall fom Commit stage detected.\n", tid);
        ret_val = true;
    }

    return ret_val;
}

template<class Impl>
inline bool
SimpleEdgeMap<Impl>::fetchInstsValid()
{
    return fromFetch->size > 0;
}

template<class Impl>
bool
SimpleEdgeMap<Impl>::block(ThreadID tid)
{
    DPRINTF(EdgeMap, "[tid:%u]: Blocking.\n", tid);

    // Add the current inputs to the skid buffer so they can be
    // reprocessed when this stage unblocks.
    skidInsert(tid);

    // If the map status is blocked or unblocking then map has not yet
    // signalled fetch to unblock. In that case, there is no need to tell
    // fetch to block.
    if (mapStatus[tid] != Blocked) {
        // Set the status to Blocked.
        mapStatus[tid] = Blocked;

        if (mapStatus[tid] != Unblocking) {
            toFetch->mapBlock[tid] = true;
            wroteToTimeBuffer = true;
        }

        return true;
    }

    return false;
}

template<class Impl>
bool
SimpleEdgeMap<Impl>::unblock(ThreadID tid)
{
    // Map is done unblocking only if the skid buffer is empty.
    if (skidBuffer[tid].empty()) {
        DPRINTF(EdgeMap, "[tid:%u]: Done unblocking.\n", tid);
        toFetch->mapUnblock[tid] = true;
        wroteToTimeBuffer = true;

        mapStatus[tid] = Running;
        return true;
    }

    DPRINTF(EdgeMap, "[tid:%u]: Currently unblocking.\n", tid);

    return false;
}

template<class Impl>
void
SimpleEdgeMap<Impl>::squash(BlockPtr &inst_block, ThreadID tid)
{
    DPRINTF(EdgeMap, "[tid:%i]: [block:%i] Squashing due to incorrect branch prediction "
            "detected at map.\n", tid, inst_block->getBlockID());

    // Send back mispredict information.
    toFetch->mapInfo[tid].branchMispredict = true;
    toFetch->mapInfo[tid].predIncorrect = true;
    toFetch->mapInfo[tid].squash = true;
    toFetch->mapInfo[tid].doneSeqNum = inst_block->getBlockID();

    toFetch->mapInfo[tid].nextPC = inst_block->getBranchTarget();
    toFetch->mapInfo[tid].branchTaken =
        inst_block->getNextBlockPC() != inst_block->getBranchTarget();

    BlockID squash_block_id = inst_block->getBlockID();

    // Might have to tell fetch to unblock.
    if (mapStatus[tid] == Blocked ||
        mapStatus[tid] == Unblocking) {
        toFetch->mapUnblock[tid] = 1;
    }

    // Set status to squashing.
    mapStatus[tid] = Squashing;

    for (int i=0; i<fromFetch->size; i++) {
        if (fromFetch->instBlocks[i]->getTid() == tid &&
            fromFetch->instBlocks[i]->getBlockID() > squash_block_id) {
            fromFetch->instBlocks[i]->setSquashed();
        }
    }

    // Clear the instruction list and skid buffer in case they have any
    // insts in them.
    while (!instBlocks[tid].empty()) {
        instBlocks[tid].pop();
    }

    while (!skidBuffer[tid].empty()) {
        skidBuffer[tid].pop();
    }

    // Squash instructions up until this one
    cpu->removeBlocksUntil(squash_block_id, tid);
}

template<class Impl>
unsigned
SimpleEdgeMap<Impl>::squash(ThreadID tid)
{
    DPRINTF(EdgeMap, "[tid:%i]: Squashing.\n",tid);

    if (mapStatus[tid] == Blocked ||
        mapStatus[tid] == Unblocking) {

        // In syscall emulation, we can have both a block and a squash due
        // to a syscall in the same cycle.  This would cause both signals to
        // be high.  This shouldn't happen in full system.
        // @todo: Determine if this still happens.
        if (toFetch->mapBlock[tid]) {
            toFetch->mapBlock[tid] = 0;
        } else {
            toFetch->mapUnblock[tid] = 1;
        }
    }

    // Set status to squashing.
    mapStatus[tid] = Squashing;

    // Go through incoming instructions from fetch and squash them.
    unsigned squash_count = 0;

    for (int i=0; i<fromFetch->size; i++) {
        if (fromFetch->instBlocks[i]->getTid() == tid) {
            fromFetch->instBlocks[i]->setSquashed();
            squash_count++;
        }
    }

    // Clear the instruction list and skid buffer in case they have any
    // inst blocks in them.
    while (!instBlocks[tid].empty()) {

        mapSquashedInstBlocks += instBlocks[tid].size();

        instBlocks[tid].pop();
    }

    while (!skidBuffer[tid].empty()) {

        mapSquashedInstBlocks += skidBuffer[tid].size();

        skidBuffer[tid].pop();
    }

    return squash_count;
}

template<class Impl>
void
SimpleEdgeMap<Impl>::skidInsert(ThreadID tid)
{
    BlockPtr inst_block = NULL;

    while (!instBlocks[tid].empty()) {
        inst_block = instBlocks[tid].front();

        instBlocks[tid].pop();

        assert(tid == inst_block->getTid());

        DPRINTF(EdgeMap,"Inserting Block[id:%lli] PC:%#x into map skidBuffer %i with RefCount %i\n",
                inst_block->getBlockID(),
                inst_block->getStartPC(),
                inst_block->getTid(),
                inst_block->getCount());

        skidBuffer[tid].push(inst_block);
    }

    // @todo: Eventually need to enforce this by not letting a thread
    // fetch past its skidbuffer
    assert(skidBuffer[tid].size() <= skidBufferMax);
}

template<class Impl>
bool
SimpleEdgeMap<Impl>::skidsEmpty()
{
    list<ThreadID>::iterator threads = activeThreads->begin();
    list<ThreadID>::iterator end = activeThreads->end();

    while (threads != end) {
        ThreadID tid = *threads++;
        if (!skidBuffer[tid].empty())
            return false;
    }

    return true;
}

template<class Impl>
void
SimpleEdgeMap<Impl>::updateStatus()
{
    bool any_unblocking = false;

    list<ThreadID>::iterator threads = activeThreads->begin();
    list<ThreadID>::iterator end = activeThreads->end();

    while (threads != end) {
        ThreadID tid = *threads++;

        if (mapStatus[tid] == Unblocking) {
            any_unblocking = true;
            break;
        }
    }

    // Map will have activity if it's unblocking.
    if (any_unblocking) {
        if (_status == Inactive) {
            _status = Active;

            DPRINTF(Activity, "Activating stage.\n");

            cpu->activateStage(CPU::MapIdx);
        }
    } else {
        // If it's not unblocking, then map will not have any internal
        // activity.  Switch it to inactive.
        if (_status == Active) {
            _status = Inactive;
            DPRINTF(Activity, "Deactivating stage.\n");

            cpu->deactivateStage(CPU::MapIdx);
        }
    }
}

template <class Impl>
void
SimpleEdgeMap<Impl>::sortInstBlocks()
{
    int blocks_from_fetch = fromFetch->size;
#ifdef DEBUG
    for (ThreadID tid = 0; tid < numThreads; tid++)
        assert(instBlocks[tid].empty());
#endif
    for (int i = 0; i < blocks_from_fetch; ++i) {
        instBlocks[fromFetch->instBlocks[i]->getTid()].push(fromFetch->instBlocks[i]);
    }
}

template<class Impl>
void
SimpleEdgeMap<Impl>::readStallSignals(ThreadID tid)
{
    if (fromExecute->executeBlock[tid]) {
        stalls[tid].execute = true;
    }

    if (fromExecute->executeUnblock[tid]) {
        assert(stalls[tid].execute);
        stalls[tid].execute = false;
    }

    if (fromCommit->commitBlock[tid]) {
        stalls[tid].commit = true;
    }

    if (fromCommit->commitUnblock[tid]) {
        assert(stalls[tid].commit);
        stalls[tid].commit = false;
    }
}

template <class Impl>
bool
SimpleEdgeMap<Impl>::checkSignalsAndUpdate(ThreadID tid)
{
    // Check if there's a squash signal, squash if there is.
    // Check stall signals, block if necessary.
    // If status was blocked
    //     Check if stall conditions have passed
    //         if so then go to unblocking
    // If status was Squashing
    //     check if squashing is not high.  Switch to running this cycle.

    // Update the per thread stall statuses.
    readStallSignals(tid);

    // Check squash signals from commit.
    if (fromCommit->commitInfo[tid].squash) {

        DPRINTF(EdgeMap, "[tid:%u]: Squashing blocks due to squash "
                "from commit.\n", tid);

        squash(tid);

        return true;
    }

    // Check ROB squash signals from commit.
    if (fromCommit->commitInfo[tid].robSquashing) {
        DPRINTF(EdgeMap, "[tid:%u]: ROB is still squashing.\n", tid);

        // Continue to squash.
        mapStatus[tid] = Squashing;

        return true;
    }

    if (checkStall(tid)) {
        return block(tid);
    }

    if (mapStatus[tid] == Blocked) {
        DPRINTF(EdgeMap, "[tid:%u]: Done blocking, switching to unblocking.\n",
                tid);

        mapStatus[tid] = Unblocking;

        unblock(tid);

        return true;
    }

    if (mapStatus[tid] == Squashing) {
        // Switch status to running if map isn't being told to block or
        // squash this cycle.
        DPRINTF(EdgeMap, "[tid:%u]: Done squashing, switching to running.\n",
                tid);

        mapStatus[tid] = Running;

        return false;
    }

    // If we've reached this point, we have not gotten any signals that
    // cause map to change its status.  Map remains the same as before.
    return false;
}

template<class Impl>
void
SimpleEdgeMap<Impl>::tick()
{
    wroteToTimeBuffer = false;

    bool status_change = false;

    toExecuteIndex = 0;

    list<ThreadID>::iterator threads = activeThreads->begin();
    list<ThreadID>::iterator end = activeThreads->end();

    sortInstBlocks();

    //Check stall and squash signals.
    while (threads != end) {
        ThreadID tid = *threads++;

        DPRINTF(EdgeMap,"Processing [tid:%i]\n",tid);
        status_change =  checkSignalsAndUpdate(tid) || status_change;

        map(status_change, tid);
    }

    if (status_change) {
        updateStatus();
    }

    if (wroteToTimeBuffer) {
        DPRINTF(Activity, "Activity this cycle.\n");

        cpu->activityThisCycle();
    }
}

template<class Impl>
void
SimpleEdgeMap<Impl>::map(bool &status_change, ThreadID tid)
{
    // If status is Running or idle,
    //     call mapInsts()
    // If status is Unblocking,
    //     buffer any instructions coming from fetch
    //     continue trying to empty skid buffer
    //     check if stall conditions have passed

    if (mapStatus[tid] == Blocked) {
        ++mapBlockedCycles;
    } else if (mapStatus[tid] == Squashing) {
        ++mapSquashCycles;
    }

    // Map should try to map as many instructions as its bandwidth
    // will allow, as long as it is not currently blocked.
    if (mapStatus[tid] == Running ||
        mapStatus[tid] == Idle) {
        DPRINTF(EdgeMap, "[tid:%u]: Not blocked, so attempting to run "
                "stage.\n",tid);

        mapInsts(tid);
    } else if (mapStatus[tid] == Unblocking) {
        // Make sure that the skid buffer has something in it if the
        // status is unblocking.
        assert(!skidsEmpty());

        // If the status was unblocking, then instructions from the skid
        // buffer were used.  Remove those instructions and handle
        // the rest of unblocking.
        mapInsts(tid);

        if (fetchInstsValid()) {
            // Add the current inputs to the skid buffer so they can be
            // reprocessed when this stage unblocks.
            skidInsert(tid);
        }

        status_change = unblock(tid) || status_change;
    }
}

template <class Impl>
void
SimpleEdgeMap<Impl>::mapInsts(ThreadID tid)
{
    // Instructions can come either from the skid buffer or the list of
    // instructions coming from fetch, depending on map's status.
    int instblocks_available = mapStatus[tid] == Unblocking ?
        skidBuffer[tid].size() : instBlocks[tid].size();

    if (instblocks_available == 0) {
        DPRINTF(EdgeMap, "[tid:%u] Nothing to do, breaking out"
                " early.\n",tid);
        // Should I change the status to idle?
        ++mapIdleCycles;
        return;
    } else if (mapStatus[tid] == Unblocking) {
        DPRINTF(EdgeMap, "[tid:%u] Unblocking, removing insts from skid "
                "buffer.\n",tid);
        ++mapUnblockCycles;
    } else if (mapStatus[tid] == Running) {
        ++mapRunCycles;
    }

    BlockPtr inst_block;

    std::queue<BlockPtr>
        &instblocks_to_map = mapStatus[tid] == Unblocking ?
        skidBuffer[tid] : instBlocks[tid];

    DPRINTF(EdgeMap, "[tid:%u]: Sending instruction to execute.\n",tid);

    while (instblocks_available > 0 && toExecuteIndex < mapWidth) {
        assert(!instblocks_to_map.empty());

        DPRINTF(EdgeMap, "Mapping inst block[Bid:%lli] with "
                "RefCount = %i\n",
                instblocks_to_map.front()->getBlockID(),
                instblocks_to_map.front()->getCount());

        inst_block = instblocks_to_map.front();

        instblocks_to_map.pop();

        DPRINTF(EdgeMap, "[tid:%u]: Processing block [id:%lli] at "
                "PC %#x with %lli insts\n",
                tid, inst_block->getBlockID(),
                inst_block->getStartPC(),
                inst_block->getBlockSize());

        if (inst_block->isSquashed()) {
            DPRINTF(EdgeMap, "[tid:%u]: Instruction %i with PC %#x is "
                    "squashed, skipping.\n",
                    tid, inst_block->getBlockID(),
                    inst_block->getStartPC());

            ++mapSquashedInstBlocks;

            --instblocks_available;

            continue;
        }

        // Map me!!!
        inst_block->map();

        toExecute->instBlocks[toExecuteIndex] = inst_block;

        ++(toExecute->size);

        assert(toExecute->size <= Impl::MaxFetchWidth);

        ++toExecuteIndex;
        ++mapMappedInstBlocks;
        --instblocks_available;
    }

    // If we didn't process all instructions, then we will need to block
    // and put all those instructions into the skid buffer.
    if (!instblocks_to_map.empty()) {
        block(tid);
    }

    // Record that map has written to the time buffer for activity
    // tracking.
    if (toExecuteIndex) {
        wroteToTimeBuffer = true;
    }
}

